import { constantRoutes } from '@/router'

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
  // 一级菜单遍历
  const res = []
  // routes.forEach((firstMenu) => {
  // const mainMenu = {
  //   name: firstMenu.name,
  //   meta: {title: firstMenu.name},
  //   hidden: true,
  //   children:[]
  // }
  // res.push(mainMenu)
  // 二级菜单遍历
  routes[0].nodes.forEach((secondMenu) => {
    const subMenu = {
      name: secondMenu.name,
      meta: {
        title: secondMenu.name
      },
      component: () => import(`@/layout`),
      path: `/`,
      // redirect: `${secondMenu.name}`,
      children: []
    }
    res.push(subMenu)
    if (secondMenu.nodes.length < 1 || !secondMenu.nodes) {
      delete subMenu.children
    } else {
      secondMenu.nodes.forEach((thirdMenu) => {
        subMenu.children.push({
          name: thirdMenu.name,
          path: `${secondMenu.name}/${thirdMenu.name}`,
          component: (resolve) => require([`@/views/${thirdMenu.url}`], resolve),
          meta: { title: thirdMenu.name, icon: thirdMenu.open_img }
        })
      })
    }
  })
  // })
  // res = [...res]
  console.info(res)
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, routes) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(routes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
